#include "protocol_manager.h"
#include "base_log.h"
#include "websocket_event_processor.h"

namespace El {
namespace Protocol {

ProtocolManager &ProtocolManager::GetInstance()
{
    static ProtocolManager instance;
    return instance;
}

ProtocolManager::~ProtocolManager()
{
    Stop();
}

bool ProtocolManager::Start()
{
    if (running_) {
        return true;
    }
    // 初始化事件队列
    event_queue_ = std::make_unique<El::Base::BlockingQueue<std::shared_ptr<El::WebServer::WebSocketEvent>>>("WebSocketEventQueue", 100);

    // 启动处理线程
    running_ = true;
    process_thread_ = std::make_unique<std::thread>(&ProtocolManager::ProcessWebSocketEvents, this);

    // 注册WebSocket处理
    auto &http_server = El::WebServer::IHttpServer::GetInstance();
    if (!http_server.RegisterWebSocketHandler(
            "^/v1/protocol$", [this](std::shared_ptr<El::WebServer::WebSocketEvent> &event) { HandleWebSocketEvent(event); })) {
        LOG_ERROR("Failed to register WebSocket handler");
        Stop();
        return false;
    }

    return true;
}

void ProtocolManager::Stop()
{
    if (!running_) {
        return;
    }

    // 停止处理线程
    running_ = false;

    // 停止队列
    if (event_queue_) {
        event_queue_->SetActive(false);
    }

    // 等待线程结束
    if (process_thread_ && process_thread_->joinable()) {
        process_thread_->join();
        process_thread_ = nullptr;
    }

    // 清理资源
    event_queue_ = nullptr;
}

void ProtocolManager::HandleWebSocketEvent(std::shared_ptr<El::WebServer::WebSocketEvent> &event)
{
    LOG_DEBUG("Received WebSocketEvent, pushing to queue: {}", event->message);

    // 将事件推送到队列
    if (event_queue_ && !event_queue_->Push(event)) {
        LOG_ERROR("Failed to push WebSocketEvent to queue: queue is full or inactive");
    }
}

void ProtocolManager::ProcessWebSocketEvents()
{
    LOG_INFO("WebSocket event processing thread started");

    while (running_) {
        // 从队列获取事件，设置超时为100ms，定期检查running_状态
        auto event = event_queue_->Pop(100);

        // 如果获取到有效事件，则处理
        if (!event->message.empty()) {
            LOG_INFO("Processing WebSocketEvent from queue: {}", event->message);

            try {
                // 使用WebSocketEventProcessor处理事件
                auto &processor = WebSocketEventProcessor::GetInstance();
                std::string response = processor.ProcessEvent(event);

                // 如果有响应消息，则发送回客户端
                if (!response.empty()) {
                    LOG_DEBUG("Sending response to client: {}", response);
                    auto &http_server = El::WebServer::IHttpServer::GetInstance();
                    if (!http_server.SendWebSocketTextMessage(event->connection, response)) {
                        LOG_ERROR("Failed to send response to client");
                    }
                }
            } catch (const std::exception &e) {
                LOG_ERROR("Exception while processing WebSocket event: {}", e.what());
            }
        }
    }

    LOG_INFO("WebSocket event processing thread stopped");
}

} // namespace Protocol
} // namespace El